#include "Map.h"

Map::Map()
{
   tileset_for_layer[L_SOL] = "test.png";
   for(int iLig = 0 ; iLig < MAP_DIM_MAX ; iLig++)
      for(int iCol = 0 ; iCol < MAP_DIM_MAX ; iCol++)
         tile_on_case[L_SOL][iLig][iCol] = 0;
}

Map::Map(const char *map_name)
{
   if(!load(map_name))
      printf("Unable to load %s\n", map_path_final.c_str());
}

Map::~Map()
{
}

bool Map::load(const char *map_name)
{
   map_path_final = string(map_name);
   map_file = fopen(map_path_final.c_str(), "r");
   if(!map_file)
      return false;

   char ts[100];
   fscanf(map_file, "%d%d%s", &mapDim.height, &mapDim.width, ts);
   tileset_for_layer[L_SOL] = ts;
   
   mapPixDim = pix_dim(mapDim.width*TILE_DIM,mapDim.height*TILE_DIM);
  
   for(int iLig = 0 ; iLig < mapDim.height ; iLig++)
      for(int iCol = 0 ; iCol < mapDim.width ; iCol++)
         fscanf(map_file, "%d", &tile_on_case[L_SOL][iLig][iCol]);
         
   fclose(map_file);
   
   return true;
}

void Map::save(const char *map_name)
{
   map_path_final = string(map_name);
   map_file = fopen(map_path_final.c_str(), "w+");
   
   fprintf(map_file, "%d %d\n%s\n", mapDim.height, mapDim.width, tileset_for_layer[L_SOL].c_str());
   
   for(int iLig = 0 ; iLig < mapDim.height ; iLig++)
   {
      for(int iCol = 0 ; iCol < mapDim.width ; iCol++)
         fprintf(map_file, "%d ", tile_on_case[L_SOL][iLig][iCol]);
      fprintf(map_file, "\n");
   }
   
   fclose(map_file);
}

void Map::save()
{
   map_file = fopen(map_path_final.c_str(), "w+");
   
   fprintf(map_file, "%d %d\n%s\n", mapDim.height, mapDim.width, tileset_for_layer[L_SOL].c_str());
   
   for(int iLig = 0 ; iLig < mapDim.height ; iLig++)
   {
      for(int iCol = 0 ; iCol < mapDim.width ; iCol++)
         fprintf(map_file, "%d ", tile_on_case[L_SOL][iLig][iCol]);
      fprintf(map_file, "\n");
   }
   
   fclose(map_file);
}

bool Map::isLoaded()
{
   return mapDim.width != 0 && mapDim.height != 0;
}

void Map::calc_coord_on_screen(pix_coord p_start)
{
   start = p_start;
   for(int iLig = 0 ; iLig < mapDim.height ; iLig++)
      for(int iCol = 0 ; iCol < mapDim.width ; iCol++) 
         coord_on_screen[L_SOL][iLig][iCol] = pix_coord((start.x+(iCol)*(TILE_DIM+space_w)),start.y+iLig*(TILE_DIM+space_h));
}
   
   
